<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px" class="advanced-search-form">
      <el-row :gutter="15">
        <!-- 第一行 -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="优惠券名称" prop="name">
            <el-input
                v-model="queryParams.name"
                placeholder="请输入优惠券名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="优惠券类型" prop="couponType">
            <el-select
                v-model="queryParams.couponType"
                placeholder="请选择优惠券类型"
                clearable
                style="width: 100%; min-width: 150px"
            >
              <el-option
                  v-for="dict in coupon_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="折扣比例" prop="discountRate">
            <el-input
                v-model="queryParams.discountRate"
                placeholder="请输入折扣比例"
                clearable
                @keyup.enter="handleQuery"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="优惠金额" prop="discountAmount">
            <el-input
                v-model="queryParams.discountAmount"
                placeholder="请输入优惠金额"
                clearable
                @keyup.enter="handleQuery"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 -->
      <el-row :gutter="15">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="最低使用金额" prop="minimumOrderAmount">
            <el-input
                v-model="queryParams.minimumOrderAmount"
                placeholder="请输入最低金额"
                clearable
                @keyup.enter="handleQuery"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用商品" prop="applicableScope">
            <el-input
                v-model="queryParams.applicableScope"
                placeholder="请输入适用商品"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="开始时间" prop="validFrom">
            <el-date-picker
                v-model="queryParams.validFrom"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="开始时间"
                style="width: 100%"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="结束时间" prop="validTo">
            <el-date-picker
                v-model="queryParams.validTo"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="结束时间"
                style="width: 100%"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 -->
      <el-row :gutter="15">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="发放数量" prop="totalCount">
            <el-input
                v-model="queryParams.totalCount"
                placeholder="请输入发放数量"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="限领次数" prop="limitPerUser">
            <el-input
                v-model="queryParams.limitPerUser"
                placeholder="请输入限领次数"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="是否可叠加使用" prop="isStackable">
            <el-select
                v-model="queryParams.isStackable"
                placeholder="请选择是否可叠加使用"
                clearable
                style="width: 100%; min-width: 150px"
            >
              <el-option
                  v-for="dict in is_stackable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="状态" prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                clearable
                style="width: 100%; min-width: 150px"
            >
              <el-option
                  v-for="dict in status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24" style="text-align: right; padding-right: 10px;">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['transaction:couponInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['transaction:couponInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['transaction:couponInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['transaction:couponInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div style="overflow-x: auto;">
      <el-table
          v-loading="loading"
          :data="couponInfoList"
          @selection-change="handleSelectionChange"
          style="width: 100%; min-width: 1200px;"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" prop="id" align="center" width="100" />
        <el-table-column label="优惠券名称" prop="name" align="center" width="160" show-overflow-tooltip />
        <el-table-column label="优惠券类型" prop="couponType" align="center" width="120">
          <template #default="scope">
            <dict-tag :options="coupon_type" :value="scope.row.couponType"/>
          </template>
        </el-table-column>
        <el-table-column label="优惠券描述" prop="description" align="center" width="200" show-overflow-tooltip />
        <el-table-column label="适用的商品" prop="applicableScope" align="center" width="200" show-overflow-tooltip />
        <el-table-column label="门店限制" prop="storeLimitType" align="center" width="120" show-overflow-tooltip />
        <el-table-column label="有效时间" align="center" width="220">
          <template #default="scope">
            <div style="display: flex; justify-content: center; align-items: center; gap: 8px;">
              <span>{{ parseTime(scope.row.validFrom, '{y}-{m}-{d}') }}</span>
              <span>至</span>
              <span>{{ parseTime(scope.row.validTo, '{y}-{m}-{d}') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="发放总数量" prop="totalCount" align="center" width="120" />
        <el-table-column label="用户限领数" prop="limitPerUser" align="center" width="120" />
        <el-table-column label="叠加使用" prop="isStackable" align="center" width="100">
          <template #default="scope">
            <dict-tag :options="is_stackable" :value="scope.row.isStackable"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" align="center" width="100">
          <template #default="scope">
            <dict-tag :options="status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div style="white-space: nowrap;">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['transaction:couponInfo:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['transaction:couponInfo:remove']">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券类型管理对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="couponInfoRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠券名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入优惠券名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠券类型" prop="couponType">
              <el-select
                  v-model="form.couponType"
                  placeholder="请选择优惠券类型"
                  style="width: 100%"
                  @change="handleCouponTypeChange"
              >
                <el-option
                    v-for="dict in coupon_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="优惠券描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" rows="3" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
                label="折扣比例"
                prop="discountRate"
                v-if="form.couponType === 3"
            >
              <el-input
                  v-model="form.discountRate"
                  placeholder="请输入折扣比例"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                label="优惠金额"
                prop="discountAmount"
                v-if="form.couponType !== 3 && form.couponType !== null"
            >
              <el-input
                  v-model="form.discountAmount"
                  placeholder="请输入优惠金额"
              >
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最低使用金额限制" prop="minimumOrderAmount">
              <el-input v-model="form.minimumOrderAmount" placeholder="请输入最低使用金额限制">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用的商品" prop="applicableScope">
              <el-input v-model="form.applicableScope" placeholder="请输入适用的商品" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="validFrom">
              <el-date-picker clearable
                              v-model="form.validFrom"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择开始时间"
                              style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="validTo">
              <el-date-picker clearable
                              v-model="form.validTo"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择结束时间"
                              style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发放总数量" prop="totalCount">
              <el-input v-model="form.totalCount" placeholder="请输入发放总数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户限领次数" prop="limitPerUser">
              <el-input v-model="form.limitPerUser" placeholder="请输入每个用户限领次数" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否可叠加使用" prop="isStackable">
              <el-select v-model="form.isStackable" placeholder="请选择是否可叠加使用" style="width: 100%">
                <el-option
                    v-for="dict in is_stackable"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in status"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="删除标志" prop="delFlag" v-if="form.delFlag !== null">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CouponInfo">
import { listCouponInfo, getCouponInfo, delCouponInfo, addCouponInfo, updateCouponInfo } from "@/api/transaction/couponInfo"
//导入字典序需要两行代码！
const { proxy } = getCurrentInstance()
const { coupon_type, status, is_stackable } = proxy.useDict('coupon_type', 'status', 'is_stackable')

const couponInfoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    couponType: null,
    discountRate: null,
    discountAmount: null,
    minimumOrderAmount: null,
    applicableScope: null,
    storeLimitType: null,
    validFrom: null,
    validTo: null,
    totalCount: null,
    limitPerUser: null,
    isStackable: null,
    status: null,
  },
  rules: {
    name: [
      { required: true, message: "优惠券名称不能为空", trigger: "blur" }
    ],
    couponType: [
      { required: true, message: "优惠券类型不能为空", trigger: "change" }
    ],
    validFrom: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    validTo: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询优惠券类型管理列表 */
function getList() {
  loading.value = true
  listCouponInfo(queryParams.value).then(response => {
    couponInfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 新增方法：处理优惠券类型变化
const handleCouponTypeChange = (val) => {
  // 根据类型清空不需要的字段
  if (val === 3) {
    form.value.discountAmount = null
  } else {
    form.value.discountRate = null
  }
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    description: null,
    couponType: null,
    discountRate: null,
    discountAmount: null,
    minimumOrderAmount: null,
    applicableScope: null,
    storeLimitType: null,
    validFrom: null,
    validTo: null,
    totalCount: null,
    limitPerUser: null,
    isStackable: null,
    useDescription: null,
    showOrder: null,
    status: null,
    delFlag: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("couponInfoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加优惠券类型管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCouponInfo(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改优惠券类型管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCouponInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCouponInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除优惠券类型管理编号为"' + _ids + '"的数据项？').then(function() {
    return delCouponInfo(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('transaction/couponInfo/export', {
    ...queryParams.value
  }, `couponInfo_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.advanced-search-form {
  padding: 18px 10px 0 10px;
  background: #f8f8f8;
  border-radius: 4px;
  margin-bottom: 15px;
}
.advanced-search-form .el-form-item {
  margin-bottom: 15px;
}


</style>

